package com.springcloud.tools.conf;

import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @author fuc
 * @create 2020-06-08
 */
@Configuration
public class MongoDBConfig {
  @Value("${spring.data.mongodb.clusterNodes}")
  private String clusterNodes;

  @Value("${spring.data.mongodb.user}")
  private String mongoUser;

  @Value("${spring.data.mongodb.pwd}")
  private String mongoPd;

  @Value("${mongodb.auth}")
  private String auth;

  /** mongodb集群配置 */
  @Bean(name = "mongoClient")
  public MongoClient getMongoDB() {
    MongoClient mongoDB = null;
    String[] nodes = clusterNodes.split(",");
    List<ServerAddress> sends = new ArrayList<ServerAddress>();
    for (String node : nodes) {
      String[] table = node.split(":");
      int port = Integer.parseInt(table[1]);
      ServerAddress sa = new ServerAddress(table[0], port);
      sends.add(sa);
    }
    List<MongoCredential> mongoCredentialList = new ArrayList<MongoCredential>();
    if (Objects.equals("1", auth))
      mongoCredentialList.add(
          MongoCredential.createScramSha1Credential(mongoUser, "admin", mongoPd.toCharArray()));
    mongoDB = new MongoClient(sends, mongoCredentialList);

    return mongoDB;
  }
}
